﻿using System;
using System.Text.RegularExpressions;

namespace SdmxMl.Common
{
    /// <summary>Uri syntax validator</summary>
    public class UrlValidator
    {
        /// <summary>
        /// The regular expression which validates a URL.
        /// http://flanders.co.nz/2009/11/08/a-good-url-regular-expression-repost/
        /// </summary>
        private static Regex rx = new Regex("^(?:(?:ht|f)tp(?:s?)\\:\\/\\/|~\\/|\\/)?(?:\\w+:\\w+@)?(?:(?:[-\\w]+\\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?::[\\d]{1,5})?(?:(?:(?:\\/(?:[-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?(?:(?:\\?(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?(?:[-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)(?:&(?:[-\\w~!$+|.,*:]|%[a-f\\d]{2})+=?(?:[-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*(?:#(?:[-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?$", RegexOptions.Compiled);

        private UrlValidator() { }

        /// <summary> Validates a URL.</summary>
        /// <param name="text">Url string to validate</param>
        /// <returns>True if valid</returns>
        public static bool IsValidUrl(string text)
        {
            ///Uri temp; return Uri.TryCreate(text);

            /// !!?!! Regex accepts expressions that create Uri exception
            ///return text == null ? false : rx.IsMatch(text);

            if (string.IsNullOrEmpty(text) == false)
            {
                try
                {
                    Uri u = new Uri(text);
                    return true;
                }
                catch
                {
                }
            }
            return false;
        }

    }
}
